package rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1. 建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("101.42.44.62");  // 主机
        factory.setPort(5672);            // 端口号
        factory.setUsername("rht");       // 账号
        factory.setPassword("47298");     // 密码
        factory.setVirtualHost("test");   // 虚拟主机
        Connection connection = factory.newConnection();
        // 2. 创建 channel
        Channel channel = connection.createChannel();
        // 3. 声明队列(如果存在, 可以不声明)
        channel.queueDeclare("test", true, false, false, null);
        // 4. 消费消息
        /**
         * String basicConsume(String queue 队列名称,
         *      boolean autoAck 是否自动确认,
         *      Consumer callback 接收到消息后执行的逻辑) throws IOException
         */
        DefaultConsumer consumer = new DefaultConsumer(channel){
            // 从队列中收到消息就会执行的方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到的消息 " + new String(body));
            }
        };
        channel.basicConsume("test", true, consumer);
        // 5. 关闭资源
        channel.close();
        connection.close();
    }
}
